package club.gskj.gulimall.search.service.impl;

import club.gskj.common.to.es.SkuEsModel;
import club.gskj.gulimall.search.config.GulimallElasticSearchConfig;
import club.gskj.gulimall.search.constant.EsConstant;
import club.gskj.gulimall.search.service.ProductSaveService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ProductSaveServiceImpl
 * @Description TODO
 * @Author 康纳
 * @Date 2021-02-10
 */


@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient esClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 保存到ES
        // 1. 创建索引 product 建立映射关系 mappings
        // resources\product-mappings.txt
        // 2.给es保存数据

        // 参数: BulkRequest bulkRequest, RequestOptions options
        // 批量操作
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 构造保存请求，封装信息
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);

            indexRequest.id(skuEsModel.getSkuId().toString());
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        // 保存
        BulkResponse bulk = esClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        // TODO 是否有错误,及时处理
        boolean b = bulk.hasFailures();
        List<String> ids = Arrays.asList(bulk.getItems()).stream().map(item -> item.getId()).collect(Collectors.toList());
        log.info("商品上架成功: {}, bulkRequest参数: {},", ids, bulkRequest.toString());
        return b;
    }
}
